<script>
  import { tick } from 'svelte'
  let text = 'Select some text and hit the tab key to toggle uppercase'

  function handleKeyDown(event) {
    if (event?.key !== 'Tab') return

    if (event.target) {
      const { selectionStart, selectionEnd, value } = event.target
      const selection = value.slice(selectionStart, selectionEnd)

      const replacement = /[a-z]/.test(selection)
        ? selection.toUpperCase()
        : selection.toLowerCase()

      text =
        value.slice(0, selectionStart) + replacement + value.slice(selectionEnd)

      tick().then(() => {
        event.target.selectionStart = selectionStart
        event.target.selectionEnd = selectionEnd
      })
    }
  }
</script>

<textarea bind:value={text} on:keydown|preventDefault={handleKeyDown} />

<style>
  textarea {
    width: 100%;
    height: 200px;
  }
</style>
